package com.eleme.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.eleme.dao.impl.UDaoFactory;
import com.eleme.entity.Sample;
import com.eleme.service.impl.SampleServiceImpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Servlet implementation class SampleList
 */
public class SampleList extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(request.getParameter("aaa") + " " + request.getParameter("bbb"));
		//在这里获取ajax传回来的数据，并传给service类
		response.setContentType("text/html;charset=UTF-8"); //避免乱码
		SampleServiceImpl service = new SampleServiceImpl(UDaoFactory.getInstance());
		List<Sample> li = service.getAll();
		Gson gson = new GsonBuilder().create();
		String json = gson.toJson(li);
		PrintWriter out = response.getWriter();
		out.print(json);
//		out.flush();
//		out.close();
		response.setContentType("text/html;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");
		response.getWriter().println(new GsonBuilder().create().toJson(new SampleServiceImpl(UDaoFactory.getInstance()).getAll()));
		//调用service返回结果，包装成json
	}

}
